package thread;

import java.util.ArrayList;
import java.util.List;

/**
 * @author DBX
 * @effect 生产者和消费者
 *  生产10个 消费10
 * @date 2021/09/10/21:21
 */
public class ProducersAndConsumers {
    public static void main(String[] args) {
        List list = new ArrayList();
        Thread t = new Thread(new Produces(list));
        Thread t1 = new Thread(new Consumers(list));
        t.setName("生产者");
        t1.setName("消费者");
        t.start();
        t1.start();
    }
}

class Produces implements Runnable {
    private List list;

    public Produces(List list) {
        this.list = list;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (list){
            if (list.size() >= 10) {
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            while (list.size()<10) {
                Object o = new Object();
                list.add(o);
                System.out.println(Thread.currentThread().getName() + "----->" + o);
                System.out.println(list.size());
            }
            list.notifyAll();
        }}
    }
}
class Consumers implements  Runnable{
    private List list;

    public Consumers(List list) {
        this.list = list;
    }

    @Override
    public void run() {
        while (true){
            synchronized (list){
        if (list.size()==0){
            try {
                list.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
                for (int i = 9; i >=0 ; i--) {
                    Object o = list.remove(i);
                    System.out.println(Thread.currentThread().getName()+"----->"+o);
                    System.out.println(list.size());
                }
                list.notifyAll();}
    }}}
